<template>
  <div class="box">
    <van-nav-bar
      title="用户注册"
      left-text="返回"
      right-text="登录"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push('/login')"
    />
    <div class="regist">
      <h1>用户注册</h1>

      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[
            {
              required: true,
              message: '请填写用户名',
            },
            {
              pattern: /^([\u4e00-\u9fa5]{1,7}|[a-z]{1,14})$/,
              message: '用户名格式错误，最长14个英文或7个汉字',
            },
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            {
              required: true,
              message: '请填写密码',
            },
            {
              pattern:
                /((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))(?!^.*[\u4E00-\u9FA5].*$)/,
              message: '密码必须至少包含字母、数字及标点符号中的2种',
            },
          ]"
        />

        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >注册</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    async onSubmit(values) {
      const data = await this.$store.dispatch("user/regist", values);
      if (data.status === 0) {
        this.$notify({ type: "danger", message: "用户名已存在，请重试" });
      } else if (data.status === 200) {
        this.$notify({ type: "primary", message: "注册成功，请登录" });
        this.$router.replace({
          path: "/login",
          query: {
            username: values.username,
          },
        });
      } else if (data.status === 500) {
        this.$toast("服务器出错,注册失败");
      }
    },
  },
};
</script>
<style scoped>
.box {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
}
h1 {
  margin-top: 50px;
}
.regist {
  height: 100%;
  width: 100%;
  background-image: url("https://iconfont.alicdn.com/t/2c753da1-7af0-4a1f-83d6-fcde628318c7.png");
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
  flex: 1;
}
.van-form {
  width: 80%;
  height: 40%;
  margin: 80px auto;
  background-color: #fff;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 3px 8px 0 rgba(0, 0, 0, 0.19);
}
.van-button {
  margin-bottom: 10px;
}
</style>